package com.yixiang.np.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yixiang.np.annotation.SystemControllerLog;
import com.yixiang.np.constant.GlobalConstant;
import com.yixiang.np.logaop.RequestLimit;
import com.yixiang.np.model.Grid;
import com.yixiang.np.model.JqGrid;
import com.yixiang.np.model.JqPageFilter;
import com.yixiang.np.model.Json;
import com.yixiang.np.model.PageFilter;
import com.yixiang.np.model.ServiceException;
import com.yixiang.np.model.SessionInfo;
import com.yixiang.np.model.po.Dictionary;
import com.yixiang.np.model.po.Organization;
import com.yixiang.np.model.po.User;
import com.yixiang.np.model.vo.RegVo;
import com.yixiang.np.service.DictionaryServiceI;
import com.yixiang.np.service.OrganizationServiceI;
import com.yixiang.np.service.UserServiceI;
import com.yixiang.np.utils.MD5Util;


@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	private UserServiceI userService;
	
	@Autowired
	private DictionaryServiceI dictionaryService;
	
	@Autowired
	private OrganizationServiceI organizationService;

	@Value("${operator.number}")
    private int operatorNumber;
	
	@RequestMapping("/manager")
	public String manager(HttpServletRequest request) {
		String test = JSON.toJSONString(dictionaryService.combox("usertype"));
		request.setAttribute("usertypeJson",JSON.toJSONString(dictionaryService.combox("usertype")));
		return "/admin/user";
	}
	
	@RequestMapping("/dataGrid")
	@ResponseBody
	public Grid dataGrid(User user, PageFilter ph) {
		Grid grid = new Grid();
		grid.setRows(userService.dataGrid(user, ph));
		grid.setTotal(userService.count(user, ph));
		return grid;
	}
	@RequestMapping("/operatorGrid")
	@ResponseBody
	public Grid operatorGrid(User user, PageFilter ph, HttpSession session) {
		SessionInfo sessionInfo = (SessionInfo) session.getAttribute(GlobalConstant.SESSION_INFO);
		user.setOrganizationId(sessionInfo.getOrgId());
		user.setUsertype(2);
		Grid grid = new Grid();
		grid.setRows(userService.dataGrid(user, ph));
		grid.setTotal(userService.count(user, ph));
		return grid;
	}
	
	
	@RequestMapping("/editPwdPage")
	public String editPwdPage(HttpServletRequest request) {
		return "/admin/userEditPwd";
	}
	
	@RequestMapping("/editUserPwd")
	@ResponseBody
	@SystemControllerLog(module="系统管理",methods="用户管理-修改密码")
	public Json editUserPwd(HttpServletRequest request,String oldPwd, String pwd) {
		SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(GlobalConstant.SESSION_INFO);
		Json j = new Json();
		try {
            User u = userService.get(sessionInfo.getId());
            if(MD5Util.md5(oldPwd).equals(u.getPassword())){
                userService.editUserPwd(sessionInfo, oldPwd, pwd);
                j.setSuccess(true);
                j.setMsg("密码修改成功！");
            }else{
                j.setSuccess(false);
                j.setMsg("原始密码错误！");
            }
		} catch (Exception e) {
			j.setMsg(e.getMessage());
		}
		return j;
	}
	
	@RequestMapping("/addPage")
	public String addPage(HttpServletRequest request) {
		request.setAttribute("sexList", GlobalConstant.sexlist);
		return "/admin/userAdd";
	}
	
	@RequestMapping("/add")
	@ResponseBody
	@SystemControllerLog(module="系统管理",methods="用户管理-添加用户")
	public Json add(User user) {
		Json j = new Json();
		User u = userService.getByLoginName(user);
		if(u!=null){
			j.setMsg("用户名已存在!");
		}else{
			try {
				userService.add(user);
				j.setSuccess(true);
				j.setMsg("添加成功！");
			} catch (Exception e) {
				j.setMsg(e.getMessage());
			}
			
		}
		return j;
	}
	
	@RequestMapping("/get")
	@ResponseBody
	public User get(Long id) {
		return userService.get(id);
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	@SystemControllerLog(module="系统管理",methods="用户管理-删除用户")
	public Json delete(Long id) {
		Json j = new Json();
		try {
			userService.delete(id);
			j.setMsg("删除成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg(e.getMessage());
		}
		return j;
	}
	
	@RequestMapping("/editPage")
	public String editPage(HttpServletRequest request, Long id) {
		User u = userService.get(id);
		request.setAttribute("user", u);
		request.setAttribute("sexList", GlobalConstant.sexlist);
		return "/admin/userEdit";
	}
	
	@RequestMapping("/edit")
	@ResponseBody
	@SystemControllerLog(module="系统管理",methods="用户管理-修改用户")
	public Json edit(User user) {
		Json j = new Json();
		try {
			
			//判断用户名是否存在
			User u = userService.get(user.getId());
			if(u.getLoginname().equals(user.getLoginname())){//如果用户名没变
				userService.edit(user);
			}else{
				User us = userService.getByLoginName(user);
				if(us!=null){
					j.setSuccess(false);
					j.setMsg("用户名已存在!");
					return j;
				}
				userService.edit(user);
			} 
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (ServiceException e) {
			j.setMsg(e.getMessage());
		}
		return j;
	}
	@RequestMapping("/combox/{roleId}")
	@ResponseBody
	public List<Dictionary> combox(@PathVariable String roleId) {
		return userService.combox(roleId);
	}
	@RequestMapping("/regPage")
	public String regPage(HttpServletRequest request) {
		request.setAttribute("sexList", GlobalConstant.sexlist);
		return "/reg";
	}
	@RequestMapping("/checkUser")
	@ResponseBody
	public Json checkUsername(String username) {
		Json j = new Json();
		try {
			User user = new User();
			user.setLoginname(username);
			User u = userService.getByLoginName(user);
			if(u!=null){
				j.setSuccess(false);
				j.setMsg("用户名已存在!");
			}else{
				j.setSuccess(true);
				j.setMsg("用户名可以用！");
			}
		} catch (ServiceException e) {
			j.setSuccess(false);
			j.setMsg("系统错误");
		}
		return j;
	}
	
	@RequestMapping("/reg")//采购商注册
	@RequestLimit(count=5,time=60000)
	@ResponseBody
	@SystemControllerLog(module="采购商注册",methods="采购商用户注册")
	public Json regUser(RegVo reg,HttpServletRequest request, HttpSession session) {
		Json j = new Json();
		try {
			//判断验证码是否正确
//			String kaptchaExpected = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//			String kaptchaReceived = reg.getVerifycode();
//			if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) {
//				j.setSuccess(false);
//				j.setMsg("验证码不正确！");
//				return j;
//			}
			//判断用户名是否存在
			User user = new User();
			user.setLoginname(reg.getUsername());
			User u = userService.getByLoginName(user);
			if(u!=null){
				j.setSuccess(false);
				j.setMsg("用户名已存在!");
				return j;
			}
			//保存用户信息
			userService.regUser(reg);
			j.setSuccess(true);
			j.setMsg("注册成功");
		} catch (ServiceException e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("系统错误");
		}
		return j;
	}
	@RequestMapping("/regSupplier")//供应商注册
	@RequestLimit(count=5,time=60000)
	@ResponseBody
	@SystemControllerLog(module="供应商注册",methods="供应商用户注册")
	public Json regSupplierUser(RegVo reg,HttpServletRequest request, HttpSession session) {
		Json j = new Json();
		try {
			//判断用户名是否存在
			User user = new User();
			user.setLoginname(reg.getUsername());
			User u = userService.getByLoginName(user);
			if(u!=null){
				j.setSuccess(false);
				j.setMsg("用户名已存在!");
				return j;
			}
			//保存用户信息
			userService.regSupplierUser(reg);
			j.setSuccess(true);
			j.setMsg("注册成功");
		} catch (ServiceException e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("系统错误");
		}
		return j;
	}
	@RequestMapping("/toSupplierReg")
	public String toSupplierReg() {
		return "/supplierReg";
	}
	@RequestMapping("/operatorQuery")
	public String operatorQuery() {
		return "/admin/operator";
	}
	@RequestMapping("/toOperatorAdd")
	public String toOperatorAdd() {
		return "/admin/operatorAdd";
	}
	@RequestMapping("/toOperatorEdit")
	public String toOperatorEdit(HttpServletRequest request, Long id) {
		User u = userService.get(id);
		request.setAttribute("user", u);
		request.setAttribute("sexList", GlobalConstant.sexlist);
		return "/admin/operatorEdit";
	}
	
	@RequestMapping("/operatorAdd")//营业员添加
	@ResponseBody
	@SystemControllerLog(module="营业员管理",methods="营业员添加")
	public Json operatorAdd(RegVo reg,HttpServletRequest request, HttpSession session) {
		Json j = new Json();
		try {
			//判断用户名是否存在
			User user = new User();
			user.setLoginname(reg.getUsername());
			User u = userService.getByLoginName(user);
			if(u!=null){
				j.setSuccess(false);
				j.setMsg("用户名已存在!");
				return j;
			}
			SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(GlobalConstant.SESSION_INFO);
			if(sessionInfo.getUsertype().equals(2)){//普通用户不能添加营业员
				j.setSuccess(false);
				j.setMsg("普通用户不能添加营业员！");
				return j;
			}
			Integer count = userService.getOperatorCountByOrg(sessionInfo.getOrgId());
			if(count.intValue() > operatorNumber){//如果超过配置数量 提示
				j.setSuccess(false);
				j.setMsg("营业员最多可以添加"+String.valueOf(operatorNumber)+"人！");
				return j;
			}
			userService.operatorAdd(reg,sessionInfo.getOrgId());
			j.setSuccess(true);
			j.setMsg("添加成功");
		} catch (ServiceException e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("系统错误");
		}
		return j;
	}
	@RequestMapping("/resetPwd")//采购商注册
	@ResponseBody
	@SystemControllerLog(module="营业员管理",methods="营业员重置密码")
	public Json resetPwd(String id, String password) {
		Json j = new Json();
		try {
			userService.resetPwd(id, password);
			j.setSuccess(true);
			j.setMsg("重置密码成功");
		} catch (ServiceException e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("系统错误");
		}
		return j;
	}
	
	//獲取用戶組織信息
	@RequestMapping("/imList")
	@ResponseBody
	public JSONObject imList(HttpSession session) {
		JSONObject j = new JSONObject();
		try {
			SessionInfo sessionInfo = (SessionInfo) session.getAttribute(GlobalConstant.SESSION_INFO);
			List<User> list = userService.getUserByOrgid(sessionInfo.getOrgId());
			j.put("code", 0);
			j.put("msg", "");
			JSONObject data = new JSONObject();
			JSONArray friend = new JSONArray();
			JSONObject group = new JSONObject();
			group.put("groupname", sessionInfo.getOrgName());
			group.put("id", sessionInfo.getOrgId());
			group.put("online", "");
			JSONArray uList = new JSONArray();
			for (User u : list) {
				JSONObject user = new JSONObject();
				if(!sessionInfo.getId().equals(u.getId())){
					user.put("username", u.getName());
					user.put("id", u.getId());
					user.put("avatar", "");
					user.put("sign", u.getOrganizationName());
				    uList.add(user);
				}
			}
			group.put("list", uList);
			friend.add(group);
			data.put("friend", friend);
			j.put("data", data);
			System.out.println(j.toJSONString());
		} catch (ServiceException e) {
			e.printStackTrace();
			j.put("code", 1);
			j.put("msg", "用戶獲取失敗");
		}
		return j;
	}
	/**
	 * 修改採購商和供應商信息
	 * @param session
	 * @return
	 */
	@RequestMapping("/updateInfo")
	@ResponseBody
	public Json updateInfo(String nickname, String address, String contact, String mobile,
			String telphone, String email,String type, HttpSession session) {
		Json j = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) session.getAttribute(GlobalConstant.SESSION_INFO);
			User u = userService.get(sessionInfo.getId());
			if("1".equals(type)){//从新提交的 改状态为待审核
				u.setState(GlobalConstant.TOAUDIT);
			}
			u.setName(nickname);
			u.setEmail(email);
			u.setPassword(null);
			userService.edit(u);
			sessionInfo.setName(nickname);
			sessionInfo.setEmail(email);
			session.setAttribute(GlobalConstant.SESSION_INFO, sessionInfo);
			Organization org = organizationService.get(sessionInfo.getOrgId());
			org.setAddress(address);
			org.setContact(contact);
			org.setMobile(mobile);
			org.setTelphone(telphone);
			organizationService.edit(org);
			j.setSuccess(true);
			j.setMsg("信息修改成功");
		} catch (ServiceException e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("系统错误");
		}
		return j;
	}
	//查询采购商待审核列表
	@RequestMapping("/selectNoAudit")
	@ResponseBody
	public JqGrid selectNoAudit(JqPageFilter filter, String username,String nickname,
							  String company,String contact,
							  Integer state,Integer ownerId ){
		JqGrid jq = new JqGrid();
		List<RegVo> list = null;
		PageInfo<RegVo> pageInfo = null;
		try {
			PageHelper.startPage(filter.getPage(),filter.getRows());
			list = userService.selectNoAudit(username,nickname,company,contact,state,ownerId);
			if(list != null){
				pageInfo = new PageInfo<>(list);
				jq.setPage(filter.getPage());
				jq.setRows(pageInfo.getList());
				jq.setRecords(pageInfo.getTotal());
				jq.setTotal(filter.getRows());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jq;
	}

	//采购商注册，平台审核通过

	@RequestMapping("/audit/{id}")
	@ResponseBody
	@SystemControllerLog(module="采购商注册",methods="注册审核")
	public Json auditSuccess(@PathVariable Integer id,Integer state ,String remark){
		Json json = new Json();
		try {
			userService.auditSucess(id,state,remark);
			json.setMsg("审核成功!");
			json.setSuccess(true);
		}catch (Exception e){
			e.printStackTrace();
			json.setMsg("审核失败!");
		}
		return  json;
	}
	//采购商注册，通过用户ID查用户信息
	@RequestMapping("/selectInfoById/{id}")
	@ResponseBody
	public RegVo selectInfoById(@PathVariable Integer id){
		RegVo rv = null;
		try {
			rv = userService.selectInfoById(id);
		}catch (Exception e){
			e.printStackTrace();
		}
		return  rv;
	}


}
